/*
 * (C) Copyright 2012, by Tim Xie.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.superapk.diamond.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

/**
 * 常用的Android bitmap常用处理工具类
 * 
 * @author     Tim Xie [tim.xie2008@gmail.com]
 * @date 2013-1-23
 * 
 */

public class BitmapUtil {

	/**
	 * 创建指定缩放的图片
	 * @param activity 当前Activity
	 * @param uri 图片的Uri
	 * @param imageSize 制定缩放后的图片尺寸
	 * @return 缩放后的图片
	 * @throws IOException
	 */
	public static Bitmap createThumbnailBitmap(Activity activity, Uri uri, int imageSize) throws IOException {
		//通过预读获取bitmap获取图片的宽和高
		InputStream input = activity.getContentResolver().openInputStream(uri);
		BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
		onlyBoundsOptions.inJustDecodeBounds = true;
		onlyBoundsOptions.inDither = true;
		onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
		BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
		input.close();
		if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
			return null;
		//计算较长的边
		int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
				: onlyBoundsOptions.outWidth;
		//计算缩放比例
		double ratio = (originalSize > imageSize) ? (originalSize / imageSize)
				: 1.0;
		BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
		int sampleSize = Integer.highestOneBit((int) Math.floor(ratio));
		sampleSize = sampleSize < 1 ? 1 : sampleSize;
		bitmapOptions.inSampleSize = sampleSize;
		bitmapOptions.inDither = true;
		bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
		input = activity.getContentResolver().openInputStream(uri);
		Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
		input.close();
		
		return bitmap;
	}
	
	/**
	 * 位图转成数组
	 * @param bitmap
	 * @return
	 * @throws IOException 
	 */
	public static byte[] bitmapToByteArray(Bitmap bitmap) throws IOException{
		if(bitmap != null){
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
			byte[] bitmapBytes = baos.toByteArray();
			baos.close();
			return bitmapBytes;
		}
		return null;
	}

}
